<template>
	<cl-drawer
		ref="drawer"
		:props="{
			title: '退款信息编辑',
			size: '700px',
			appendToBody: true
		}"
		show-confirm
		confirm-text="保存"
		@close="reset"
		@confirm="submit"
		:saving="saving"
	>
		<el-form ref="form" label-position="top" :model="form" :rules="rules">
			<el-form-item label="基本信息">
				<el-card shadow="never">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="退款日期" prop="refund_date">
								<cl-date-picker
									v-model="form.refund_date"
									placeholder="选择日期"
									style="width: 100%"
									value-format="yyyy-MM-dd"
									:clearable="false"
									disabled
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="退款人姓名" prop="refund_user_name">
								<el-input
									v-model="form.refund_user_name"
									placeholder="请输入退款人姓名"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="退款项目" prop="items">
								<cl-select
									v-model="form.itemsCheck"
									placeholder="请选择退款项目"
									style="width: 100%"
									multiple
									collapse-tags
									clearable
									filterable
									@change="calcRefundCost"
								>
									<el-option
										v-for="item in itemsList"
										:key="item.list_id"
										:label="item.prod_name"
										:value="item.list_id"
									/>
								</cl-select>
							</el-form-item>
						</el-col>

						<!-- <el-col :span="12">
							<el-form-item label="退款方式" prop="back_type">
								<cl-select
									v-model="form.back_type"
									placeholder="请选择退款方式"
									style="width: 100%"
								>
									<el-option
										v-for="(item, index) in backType"
										:key="index"
										:label="item.label"
										:value="item.value"
									/>
								</cl-select>
							</el-form-item>
						</el-col> -->

						<el-col :span="12">
							<el-form-item label="退款类型" prop="refund_type">
								<cl-select
									v-model="form.refund_type"
									placeholder="请选择退款类型"
									style="width: 100%"
								>
									<el-option
										v-for="item in $const.REFUND_TYPE"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									/>
								</cl-select>
							</el-form-item>
						</el-col>
						<!-- 退款项目编辑 -start -->
						<el-col :span="24" v-if="form.items.length > 0">
							<el-table border :data="form.items">
								<el-table-column
									label="退款项目名称"
									prop="prod_name"
									min-width="180"
									:showOverflowTooltip="true"
								/>
								<el-table-column
									label="申请金额"
									prop="refund_money"
									width="90"
								></el-table-column>
								<el-table-column label="退款金额" prop="price" width="170">
									<template slot-scope="{ row, $index }">
										<div class="flex flex-align-center">
											<el-form-item
												:prop="`items[${$index}].actual_money`"
												:rules="rules.actual_money"
												style="margin-bottom: 0"
											>
												<el-input
													v-model="row.actual_money"
													placeholder="请输入退款金额"
													oninput="value=value.replace(/[^\d^\.]/g,'')"
													@blur="calcActualMoney"
													style="flex: 1"
												>
													<template slot="prepend">￥</template>
												</el-input>
											</el-form-item>
										</div>
									</template>
								</el-table-column>
								<!-- <el-table-column label="操作" width="80">
								<template slot-scope="{ $index: index }">
									<el-button @click="deleteServe(index)">删除</el-button>
								</template>
							</el-table-column> -->
							</el-table>
						</el-col>
						<!-- 退款项目编辑 -end -->
						<el-col :span="12">
							<el-form-item label="银行" prop="bank_type">
								<cl-select
									v-model="form.bank_type"
									placeholder="请选择银行"
									style="width: 100%"
								>
									<el-option
										v-for="(item, index) in bankTypes"
										:key="index"
										:label="item.label"
										:value="item.value"
									/>
								</cl-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="持卡人" prop="bank_name">
								<el-input v-model="form.bank_name" placeholder="请输入持卡人" />
							</el-form-item>
						</el-col>

						<el-col :span="12">
							<el-form-item label="退款人账号" prop="back_account">
								<el-input
									oninput="value=value.replace(/[\u4e00-\u9fa5]/ig,'')"
									v-model="form.back_account"
									@blur="form.back_account = $event.target.value"
									placeholder="请填写退款人账号"
								/>
							</el-form-item>
						</el-col>

						<el-col :span="12">
							<el-form-item label="订单总额 " prop="pay_amount">
								<el-input v-model="form.pay_amount" disabled />
							</el-form-item>
						</el-col>

						<el-col :span="12">
							<el-form-item label="退款申请金额 " prop="refund_money">
								<el-input
									oninput="value=value.replace(/[^\d^\.]/g,'')"
									v-model="form.refund_money"
									@input="changeInterception"
									placeholder="请输入退款金额"
									disabled
								/>
							</el-form-item>
						</el-col>

						<el-col :span="12">
							<el-form-item label="实际退款金额 " prop="actual_money">
								<el-input
									oninput="value=value.replace(/[^\d^\.]/g,'')"
									v-model="form.actual_money"
									placeholder="请输入实际退款金额"
									@input="changeActualMoney"
									disabled
								/>
							</el-form-item>
						</el-col>

						<el-col :span="12">
							<el-form-item label="截留金额" prop="interception">
								<el-input
									oninput="value=value.replace(/[^\d^\.]/g,'')"
									disabled
									v-model="form.interception"
									placeholder="请输入截留金额"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="退款成本" prop="refund_cost">
								<el-input
									class="clear-number-input"
									type="number"
									v-model="form.refund_cost"
									placeholder="请输入退款成本"
									@input="changeInterception"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="责任老师" prop="responsible_id">
								<cl-select
									v-model="form.responsible_id"
									filterable
									placeholder="请选择责任老师"
									collapse-tags
									multiple
									style="width: 100%"
								>
									<el-option
										v-for="item in teacherList"
										:key="item.user_id"
										:label="item.user_name"
										:value="item.user_id"
									/>
								</cl-select>
							</el-form-item>
						</el-col>
					</el-row>
				</el-card>
			</el-form-item>
			<el-form-item label="退款原因" prop="operate_mes">
				<el-input
					v-model="form.operate_mes"
					placeholder="请填写退款原因"
					type="textarea"
					:rows="3"
				/>
			</el-form-item>

			<el-form-item label="支付信息" style="margin-bottom: 0">
				<el-table
					:data="form.orderNumberList.length ? form.orderNumberList : []"
					border
					stripe
					class="mb-2 table"
				>
					<el-table-column type="index" label="#" width="80" align="center" />
					<el-table-column prop="num" label="付款订单号" align="left">
						<template #default="{ row }">
							<el-input v-model="row.pay_order_no" placeholder="请输入付款订单号" />
						</template>
					</el-table-column>
					<el-table-column prop="num" label="支付方式" width="150" align="left">
						<template #default="{ row }">
							<cl-select
								v-model="row.pay_type"
								filterable
								placeholder="请选择支付方式"
								clearable
								style="width: 100%"
							>
								<el-option
									v-for="item in ORDER_PAY_TYPE"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								/>
							</cl-select>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="120" align="center">
						<template #default="{ scope, $index }">
							<template v-if="form.orderNumberList.length == $index + 1">
								<el-button icon="el-icon-plus" @click="onAddOrderNumberList"/>
								<el-button icon="el-icon-minus" v-if="form.orderNumberList.length != 1" @click="onDelOrderNumberList($index)" />
							</template>
							<el-button icon="el-icon-minus" v-else @click="onDelOrderNumberList($index)" />
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
			<el-form-item label="上传图片" prop="images">
				<cl-upload
					multiple
					:limit="5"
					:limit-size="5"
					list-type="picture-card"
					ref="uploads"
					v-model="form.images"
				/>
				<div class="s-tips">最多可上传5张图片，文件小于3M</div>
			</el-form-item>
			<el-form-item label="业绩备注" prop="achieve_remark">
				<el-input
					v-model="form.achieve_remark"
					placeholder="请填写业绩备注"
					type="textarea"
					:rows="3"
				/>
			</el-form-item>
			<!-- <el-row type="flex" justify="end">
				<div class="refundtotal">
					合计退款：<span class="color-primary"
						>￥{{ Number(form.refund_money) - Number(form.interception) }}</span
					>
				</div>
			</el-row>
			<el-row type="flex" justify="end">
				<div class="refundtotal f-12">
					截留金额：<span class="color-primary"
						>￥{{ form.interception ? form.interception : 0 }}</span
					>
				</div>
			</el-row> -->
		</el-form>
		<template #left-footer>
			<el-row type="flex" justify="end">
				<div class="refundtotal">
					合计退款：<span class="color-primary">￥{{ refundtotal }}</span>
				</div>
			</el-row>
			<el-row type="flex" justify="end">
				<div class="refundtotal f-12">
					截留金额：<span class="color-primary">￥{{ form.interception }}</span>
				</div>
			</el-row>
		</template>
	</cl-drawer>
</template>
<script>
	import dayjs from "dayjs";
	import CONSTMAP from "@/constant"
	export default {
		name: "oa-refund-info-edit",
		data() {
			const ruleFn = (msg) => {
				return (rule, value, callback) => {
					const { interception, refund_money } = this.form;
					if (!interception) {
						return callback();
					}
					if (!value) {
						return callback();
					}
					if (Number(interception) > Number(refund_money)) {
						return callback(new Error(msg));
					}
					return callback();
				};
			};
			return {
				ORDER_PAY_TYPE: CONSTMAP.ORDER_PAY_TYPE,
				info: {
					items_list: []
				},
				callback: null,
				saving: false,
				backType: [
					{ label: "微信", value: 1 },
					{ label: "支付宝", value: 2 },
					{ label: "银行卡", value: 3 }
				],
				form: {
					oa_id: "",
					refund_date: dayjs().format("YYYY-MM-DD"),
					bank_type: "",
					// back_type:"",
					refund_type: "",
					bank_name: "",
					refund_money: "",
					actual_money: "", //实际退款金额
					refund_user_name: "",
					back_account: "",
					interception: "",
					operate_mes: "",
					images: "",
					operate_state: 2,
					pay_amount: "",
					itemsCheck: [],
					items: [],
					refund_cost: 0, // 退款成本
					achieve_remark: "",
					responsible_id: [],
					orderNumberList: [{
						pay_order_no: "",
						pay_type: "",
					}]
				},
				rules: {
					refund_date: [{ required: true, message: "请选择退款日期" }],
					refund_money: [{ required: true, message: "请填写退款金额" }],
					// back_type: [{ required: true, message: "请选择退款方式"}],
					actual_money: [{ required: true, message: "请填写实际退款金额" }],
					// responsible_id: [{ required: true, message: "请选择责任老师" }],
					refund_type: [{ required: true, message: "请选择退款类型" }],
					bank_type: [{ required: true, message: "请选择银行卡类型" }],
					bank_name: [{ required: true, message: "请填写持卡人" }],
					refund_user_name: [{ required: true, message: "请填写退款人姓名" }],
					back_account: [{ required: true, message: "请填写退款人账号" }],
					operate_mes: [{ required: true, message: "请填写退款原因" }],
					// images: [{ required: true, message: "请上传图片" }],
					interception: [
						{ required: false, message: "请填写截留金额" }
						// { validator: ruleFn("截留金额不能大于退款申请金额") }
					],
					items: [{ required: true, message: "请选择退款项目" }]
				},
				teacherList: []
			};
		},
		computed: {
			refundtotal() {
				const { interception, refund_money } = this.form;
				return (refund_money || 0) - (interception || 0);
			},
			itemsList() {
				const { items_list, items = [] } = this.info;
				return (items_list || [])
					.map((v) => {
					    const indexKey = items.findIndex(e => e.list_id == v.list_id)
						return {
							...v,
							real_amount: (v?.real_amount || 0) * 1,
							costmoney: (v?.costmoney || 0) * 1,

						    refund_money: items[indexKey]?.refund_money ?? 0,
						    actual_money: items[indexKey]?.actual_money ?? 0
						}
					})
					.filter((v) => Boolean(v.real_amount));
			}
		},
		methods: {
			open(data = {}, callback) {
				this.callback = callback;
				this.$refs.drawer.create(() => {
					// Object.keys(this.form).forEach(key => {
					// 	data[key] != undefined && (this.form[key] = data[key]);
					// });
					// this.form.oa_id = data.id;
					// this.form.operate_mes = data.remark;
					// this.form.refund_date = data.create_time;
					// if (data.back_type == 0) {
					// 	this.form.back_type = "";
					// }
				});
				this.getInfo(data);
				this.getTeacherList(data)
			},
			async getInfo({ oa_id }) {
				let info = await this.$service.oa.info({ oa_id });
				// console.log(info);
				this.info = info;
				Object.keys(this.form).forEach((key) => {
					info[key] != undefined && (this.form[key] = info[key]);
				});
				this.form.operate_mes = info.remark;
				this.form.refund_date = info.created_at;
				this.form.actual_money = info.actual_money || 0;
				this.form.itemsCheck = info.items?.map(e => e.list_id) ?? []
				if (info.back_type == 0) {
					this.form.back_type = "";
				}

				this.form.orderNumberList = info.orderNumberList ? info.orderNumberList.map(e => {
					return {
						...e,
						pay_type: e.pay_type ? parseInt(e.pay_type) : ""
					}
				}) : [{
					pay_order_no: "",
					pay_type: "",
				}]
				// this.calcRefundCost();
				// this.changeInterception();
			},
			close() {
				this.$refs.drawer.close();
			},
			reset() {
				this.$refs.form.resetFields();
				this.$resetFields(this.form);
			},
			submit() {
				this.$refs.form.validate(async (valid, errors) => {
					this.showFormErr(errors);
					if (!valid) return;
					let { images, ...args } = this.form;
					if (!Array.isArray(images)) {
						images = images.split(",");
					}
					let form = { ...args, images };
					this.saving = true;
					await this.$service.oa.edit(form).done(() => {
						this.saving = false;
					});
					this.$message.success("操作成功");
					this.$emit("confirm");
					this.$bus.$off("oa-refund:refresh");
					this.close();
				});
			},

			changeInterception() {
				const { actual_money, refund_money } = this.form;
				this.form.interception = this.accSub(refund_money, actual_money);
			},
			// 实际退款金额（￥）
			changeActualMoney() {
				this.changeInterception();
				this.calcRefundCost();
			},
			// 计算退款成本
			calcRefundCost(v) {
				const { actual_money, items, itemsCheck } = this.form;
				// 实际退款金额（￥）
				let actualMoney = (actual_money || 0) * 1;
				let list = this.itemsList.filter((v) => itemsCheck.includes(v.list_id));
				// 总实际消费金额（￥）
				let allAmount = list.reduce((prev, curr) => prev + curr.real_amount, 0);
				console.log("总实际消费金额（￥）", allAmount);
				let res = list.reduce((prev, curr) => {
					// 实际消费金额（￥）
					let realAmount = curr.real_amount;
					// console.log("实际消费金额（￥）", realAmount);
					// 成本
					let costmoney = curr.costmoney;
					// 占比
					let ratio = allAmount == 0 ? 0 : realAmount / allAmount;
					// 占比退款 = 退款申请金额 x 占比
					let refundMoney = actualMoney * ratio;
					// 实际退款成本 = (占比退款 / 项目实际消费金额) x 成本
					let total = realAmount == 0 ? 0 : (refundMoney / realAmount) * costmoney;
					// console.log("item退款成本", {
					// 	allAmount,
					// 	realAmount,
					// 	costmoney,
					// 	ratio,
					// 	refundMoney,
					// 	total
					// });
					// 最后每个结果相加
					return prev + total;
				}, 0);
				this.form.refund_cost = this.toFixed(res);

				const checkArr = this.itemsList?.filter((e) => v.includes(e.list_id)) ?? []
				// this.form.items = checkArr
				this.$set(this.form, 'items', checkArr)

				this.calcActualMoney()
			},
			// 计算实际退款金额
			calcActualMoney() {
				this.form.actual_money = this.form.items.map(e => e.actual_money).reduce((prev, num) => parseFloat(num) + parseFloat(prev))

				this.changeActualMoney()
			},
			//获取人员
			async getTeacherList(row) {
				let { store_id } = row;
				this.teacherList = [];
				const { data } = await this.$service.user.list({
					dept_id: store_id,
					page_size: 1000,
					page: 1
				});
				this.teacherList = data;
			},
			// 新增订单号
			onAddOrderNumberList(e) {
				this.form.orderNumberList.push({
						pay_order_no: "",
						pay_type: "",
					});
			},
			onDelOrderNumberList(index) {
				this.form.orderNumberList.splice(index, 1);
			}
		}
	};
</script>

<style lang="scss" scoped>
	.refundtotal {
		font-size: 14px;
		color: #555555;
		margin-right: 10px;
		&.f-12 {
			font-size: 12px;
			color: #d9d9d9;
		}
	}
</style>
